package com.hanhanxiaochong.zhongxiangchuanmei.view.main.act;

import android.Manifest;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.BannerBean;
import com.hanhanxiaochong.zhongxiangchuanmei.config.HttpPostService;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.main.adapter.MainPagerAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.CustomViewPager;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.HomePageDialog;
import com.jakewharton.rxbinding.view.RxView;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseObserver;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.ResponseBase;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.main_viewpager)
    CustomViewPager mainViewpager;
    @BindView(R.id.rb_home)
    ImageView rbHome;
    @BindView(R.id.rb_shop)
    ImageView rbShop;
    @BindView(R.id.rb_order)
    ImageView rbOrder;
    @BindView(R.id.rb_my)
    ImageView rbMy;
    @BindView(R.id.main_bottom_btn)
    LinearLayout mainBottomBtn;

    //退出时间,等待时间
    private static final long EXIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    private List<View> viewList = new ArrayList<>();
    private MainPagerAdapter mainPagerAdapter;
    private HomeLayout homeLayout;
    private ShopLayout shopLayout;
    private OrderLayout orderLayout;
    private MyLayout myLayout;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        initLocation();
        homeLayout = new HomeLayout(mContext);
        shopLayout = new ShopLayout(mContext);
        orderLayout = new OrderLayout(mContext);
        myLayout = new MyLayout(mContext);
        viewList.add(homeLayout);
        viewList.add(shopLayout);
        viewList.add(orderLayout);
        viewList.add(myLayout);

        mainPagerAdapter = new MainPagerAdapter(viewList);
        mainViewpager.setAdapter(mainPagerAdapter);
        rbHome.setSelected(true);

        //6.0以上权限获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) permissionCheck();

        //首页
        RxView.clicks(rbHome)
                .filter(aVoid -> !rbHome.isSelected()).subscribe(aVoid -> {
            rbHome.setSelected(true);
            rbShop.setSelected(false);
            rbOrder.setSelected(false);
            rbMy.setSelected(false);
            mainViewpager.setCurrentItem(0);
        });
        //商城
        RxView.clicks(rbShop)
                .filter(aVoid -> !rbShop.isSelected()).subscribe(aVoid -> {
            rbHome.setSelected(false);
            rbShop.setSelected(true);
            rbOrder.setSelected(false);
            rbMy.setSelected(false);
            mainViewpager.setCurrentItem(1);
        });
        //订单
        RxView.clicks(rbOrder)
                .filter(aVoid -> !rbOrder.isSelected()).subscribe(aVoid -> {
            rbHome.setSelected(false);
            rbShop.setSelected(false);
            rbOrder.setSelected(true);
            rbMy.setSelected(false);
            mainViewpager.setCurrentItem(2);
        });
        //我的
        RxView.clicks(rbMy)
                .filter(aVoid -> !rbMy.isSelected()).subscribe(aVoid -> {
            rbHome.setSelected(false);
            rbShop.setSelected(false);
            rbOrder.setSelected(false);
            rbMy.setSelected(true);
            mainViewpager.setCurrentItem(3);
        });

        RetrofitSource.createApi(HttpPostService.class).getBanner("1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ResponseBase<List<BannerBean>>>(this) {
                    @Override
                    public void onSuccess(ResponseBase<List<BannerBean>> response) {
                        checkIsDiscount(response);
                    }
                });
    }

    private void checkIsDiscount(ResponseBase<List<BannerBean>> list) {
        RetrofitSource.createApi(HttpPostService.class).is_discount(SharedPreferencesUtil.getsInstances(MainActivity.this).getLoginInfo().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ResponseBase<Map<String, Integer>>>(this) {
                    @Override
                    public void onSuccess(ResponseBase<Map<String, Integer>> response) {
                        Object object = response.getData();
                        if ((int) ((Map) object).get("type") == 0) {
                            List<BannerBean> data = list.getData();
//                        HomePageDialog homePageDialog1 = HomePageDialog.newInstance(data.get(0).getSlide_pic(), data.get(0).getSlide_url());
//                        homePageDialog1.show(getSupportFragmentManager(), "ads");
                            HomePageDialog homePageDialog2 = HomePageDialog.newInstance(data.get(0).getSlide_pic(),
                                    data.get(0).getSlide_url() + "?uid=" + SharedPreferencesUtil.getsInstances(MainActivity.this).getLoginInfo().getU_id());
                            homePageDialog2.show(getSupportFragmentManager(), "questions");
                        }
                    }
                });
    }

    //权限申请(6.0以上)
    private void permissionCheck() {
        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
    }

    @PermissionSuccess(requestCode = 100)
    public void successOpenCamera() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        String city = aMapLocation.getCity();
        homeLayout.setCity(city);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event) {
        if (event.getMessage().equals("shopping_cart")) {
            rbHome.setSelected(false);
            rbShop.setSelected(true);
            rbOrder.setSelected(false);
            rbMy.setSelected(false);
            mainViewpager.setCurrentItem(1);
        } else if (event.getMessage().equals("login_out")) {
            finish();
        } else if (event.getMessage().equals("appoint")) {
            rbHome.setSelected(false);
            rbShop.setSelected(false);
            rbOrder.setSelected(true);
            rbMy.setSelected(false);
            mainViewpager.setCurrentItem(2);
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - TOUCH_TIME < EXIT_TIME) {
            quitApp();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            ToastUtils.showToast(R.string.press_again_to_exit);
        }
    }

    private void quitApp() {
        homeLayout.unregisterEventbus();
        myLayout.unregisterEventbus();
        EventBus.getDefault().unregister(this);
        //finish所有activity
        appManager.killAll();
        System.exit(0);
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
